package com.atguigu.bookcity.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.atguigu.bookcity.entity.User;
import com.atguigu.bookcity.exception.BookCityException;
import com.atguigu.bookcity.service.EmailService;
import com.atguigu.bookcity.service.UserService;
import com.atguigu.bookcity.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class EmailServiceImpl implements EmailService {
    @Resource
    private JavaMailSender mailSender;

    @Resource
    private RedisUtil redisUtil;
    @Value("${spring.mail.username}")
    private String from;
    @Resource
    private UserService userService;

    @Override
    public void getEmailCodeForRegister(String email) {
        int count = userService
                .getBaseMapper()
                .selectCount(new QueryWrapper<User>().eq("email", email));
        if (count != 0)
            throw new BookCityException(201, "邮箱已被注册");
        try {
            String content = RandomUtil.randomNumbers(4);
            sendEmail(email,
                    "注册码一分钟内有效,请勿泄露验!!!\n验证码为: ",
                    content);

            redisUtil.set(email, content, 60);
        } catch (MailException e) {
            throw new BookCityException(201, "邮箱发送失败");
        }
    }
    @Override
    public void sendEmail(String email, String what,String content) {
        String subject = "欢迎来到我的bookcity在线平台";
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); // 邮件发送者
        message.setTo(email); // 邮件接受者
        message.setSubject(subject); // 主题
        message.setText(what + content); // 内容
        mailSender.send(message);
    }
}
